<?php
	
	require_once(CONFIG_DIR.'reg_product_config.php');
    require_once(LIB_DIR.'api/general.php');
    require_once(LIB_DIR.'api/Snoopy.php');

	$shopDAO = GetShopDAO();
	$productDAO = GetProductDAO();
	$cityDAO = GetCityDAO();
	$productCategoryDAO = GetProductCategoryDAO();	
	$errmsg = GetMessageStack();
    
	//get by sid
	$platID = "";
	$nickName = "";
	
	/* 关键数据存在session */
	$productURL="";
	$status = "";
	$extProductID = "";

	/* 用户的提交数据 */
	$productName = "";
	$productLocation = "";
	$productPicture = "";
	$productPrice = "";
	$productCategory = "";
	$productCategoryName = "";
    $productDesc = "";

	$city="";
	$province="";    
			
	/**********************
	 * extProductID作为product附加表的key，对于逐步支持的platid，同样需要建立附加表
	 * platid为100,以producturl作为product附加表的key
	 * platid非100,以extProductID作为product附加表的key，对于逐步支持的platid，同样需要建立附加表
	 ***************************/

	if(isset($_POST['action'])){			
		
	   if( $_POST['action']=='addProduct1' )
		{ 
			
			ShowAddProductPage();		
		
		}else if($_POST['action']=='addProduct2'){
	        
			ProcessAddProduct();
		}
		
	}else{
		
		if(!isset($_GET['sid'])||!is_numeric($_GET['sid'])){
			
			edp_redirect(edp_href_link(PAGENAME_PAGE_NOT_FOUND));			
		
		}else{
			
			$sid = $_GET['sid'];
		
			if( !$shopDAO->GetShopName($sid) ){
			  
				edp_redirect(edp_href_link(PAGENAME_PAGE_NOT_FOUND));		
			
			}	
		}
				
		$status = $shopDAO->GetShopStatus($sid); //stauts为2,5,9不能添加商品

		if($status == ADDSHOP_STATUS_UNKOWNN_PLATFORM || $status == ADDSHOP_STATUS_MISS_KEY_DATA )
		{
			TransferTo('not_allow_add_product');
			return;				
		}
			
		if(isset($_GET['productURL']))
			$productURL = $_GET['productURL'];		
		
		TransferTo('add_product_1');
	} 
	
	
	
	function ShowAddProductPage()
	{
		global 	$sid,$productURL,$status,$extProductID, $nickName,$platID,
		        $productName, $productLocation, $productPicture,$productPrice,$productCategory,$productCategoryName,
		        $shopDAO, $productDAO, $cityDAO, $productCategoryDAO, $errmsg, $city, $province;
        // remove product desc by bo
        
		$snoopy = new Snoopy;
		  	
	    $productURL=edp_db_input(trim($_POST['url']));	
		$sid = edp_db_input(trim($_POST['sid'])); 
	    $vcode = trim($_POST['vcode']);	
	    
	    if( IsParaOK() == false )
	    {
	    	TransferTo('add_product_1');
			return;
	    }					    
	    	    	    				
		$platID=$shopDAO->GetPlatID($sid);
		if( !$platID ){
		  
			$errmsg->add( 'reg', '店铺不存在,不准许添加商品！' );
			TransferTo('add_product_1');
		    return; 
		}	

		$nickName = $shopDAO->GetNickName($sid);
		
		/***********************************
		 * 获取platid
		 * 
		 ***********************************/
						
		switch($platID) 
		{									
			case '0':
			{	
			    TransferTo('not_allow_add_product');		
				break;
			}
			
			case '1':
			{
				
	 			require_once(LIB_DIR.'api/taobao/Taoapi.php');

	 			if(strstr($productURL,'.taobao.') || strstr($productURL,'.tmall.') ){
		  
	 				
		 			/**
		 			 * 优化淘宝商品添加流程,先用url判断，再html判断
		 			 */
	 				
	 				$extProductID = GetTaobaoProductIDByURL($productURL);

	 				//die($extProductID);		
	 				
	 				if(edp_is_empty_string($extProductID)){

			 		    $snoopy->fetch($productURL);	 	 			 			 
			 			$html_content=$snoopy->results;		 						 
						$extProductID = GetTaobaoProductID($html_content);	 		
								 					
	 				}	
							
					if(!edp_is_empty_string($extProductID))
					{
						 $productID=$productDAO->GetProductIDByExtID($extProductID,'taobao');
	
					 	 if($productID)
						 {
			                $errmsg->add( 'reg', "该商品已添加，<a href=".edp_href_link(PAGENAME_PRODUCT_INFO,"pid=$productID").">点击查看</a>" );	 						
							TransferTo('add_product_1');
							return;							
						 }
						 else
						 {					 	
						 	 /**
						 	  * productID不存在有2种情况
						 	  * 1.该产品不存在，extProductID 不会存在product_info_taobao表中，查询不到
						 	  * 2.该产品其实存在，但是由于extProductID正则错误没有取到正确的值，导致查询不到
						 	  * 对于情况2，会完成添加产品的步骤，需要经常审核正则的正确性，通过用户报错和人工合并数据
						 	  */
	                        
							$Taoapi = new Taoapi;
							$Taoapi->method = 'taobao.taobaoke.items.detail.get';
							$Taoapi->fields = 'nick,num_iid,title,cid,pic_url,location,price,click_url';// remove product desc by bo
							$Taoapi->num_iids = $extProductID; 
							$Taoapi->pid = TAOBAOKE_ID;
							$TaobaoData = $Taoapi->Send('get','xml')->getArrayData();
	
							 if(edp_is_empty_string($Taoapi->getErrorInfo()) && isset($TaobaoData['taobaoke_item_details']) ) 
						    {	//可能有其他错误要加进判断
	
						    	$tbData = $TaobaoData['taobaoke_item_details']['taobaoke_item_detail'];
		                    	
						    	if($tbData['item']['nick']!=$nickName){
	
		                    		 $errmsg->add( 'reg', "对不起，添加的商品出错或不属于该店铺,请重新添加" );	 						
									 TransferTo('add_product_1');
									 return;	
		                    	}
	
		                    	$productName = $tbData['item']['title'];
								$productPicture = $tbData['item']['pic_url'];
								$productPrice = $tbData['item']['price'];
								//$productDesc =  $tbData['item']['desc'];  remove product desc by bo
						        
								$productCategory = $productCategoryDAO->ConvertTaobaoProductCid($tbData['item']['cid']);  						        
								$productCategoryName = $productCategoryDAO->GetProductCategoryName($productCategory);  
								
						        $productLocation = $cityDAO->GetCityID($tbData['item']['location']['state'].$tbData['item']['location']['city']);
	
						 		$city = $cityDAO->GetCityNameSimple($productLocation); 
								$provinceid = $cityDAO->GetProvinceIDByCityID($productLocation); 							
								if( $provinceid != 0)
								    $province = $cityDAO->GetCityNameSimple( $provinceid ); 
								else
								    $province = $city;
							    						        
						        $productDetailURL = 'http://item.taobao.com/item.htm?id='.$tbData['item']['num_iid']; //存入商品规范的URL
						      
						        if(empty($tbData['click_url']) || is_array($tbData['click_url'])){
						        	$clickURL = $productDetailURL;					        	
						        }else{
						        	$clickURL = $tbData['click_url'];
						        }
						        					        						        
						        edp_setsession('productDetailURL',$productDetailURL);
						        edp_setsession('clickURL',$clickURL);
						           
		                    	$status = ADDPRODUCT_STATUS_SUCCESS;		                    	
		                    }  
		                    else
		                    {
		                    	$status = ADDPRODUCT_STATUS_MISS_TAOBAOAPI_DATA;
		                    }					 								
						}
					}else
					{
						//状态2，正则获取不到extProductID，正则错误或者url为假
						//管理员审核(对于不同url重复的店铺设置status为9,人工完善数据设置status为1)
						$status = ADDPRODUCT_STATUS_MISS_KEY_DATA;
					}
					
	 			}else{

	 					//不是淘宝的商品,状态2
	 					$status = ADDPRODUCT_STATUS_MISS_KEY_DATA;

	 			}
				
				break;	
			}
			
			case '2':
			{
				
								 
			 	$snoopy->fetch($productURL);	 	 			 			 
 				$html_content=$snoopy->results;
 		 
			/*	if($nickName!=ConvertEncoding(GetDataByRegx($html_content,EACHNET_NICK_NAME),EACHNET_ENCODING))
				{
	                $errmsg->add( 'reg', "添加的商品不属于该店铺,请重新添加" );	 						
					TransferTo('add_product_1');
					return;	
				}			
			*/		
				$extProductID = GetEachnetProductID($html_content);
	
				if(!edp_is_empty_string($extProductID))
				{
					 $productID=$productDAO->GetProductIDByExtID($extProductID,'eachnet');
					 
				 	 if($productID)
					 {
		                $errmsg->add( 'reg', "该商品已添加，<a href=".edp_href_link(PAGENAME_PRODUCT_INFO,"pid=$productID").">点击查看</a>" );	 						
						TransferTo('add_product_1');
						return;		
					 }
					 else
					 {

						$productName=     ConvertEncoding(GetDataByRegx($html_content,EACHNET_PRODUCT_NAME),EACHNET_ENCODING);
						$productPrice=    GetDataByRegx($html_content,EACHNET_PRODUCT_PRICE);
						//$productLocation $productPicture productCategory productDesc 
						
						$status = ADDPRODUCT_STATUS_SUCCESS;
						
						if(edp_is_empty_string($productName)|| edp_is_empty_string($productPrice))
						{
		      	      		$status = ADDPRODUCT_STATUS_MISS_REG_DATA;
				   		}							
					 }
				}
				else
				{
				
					$status = ADDPRODUCT_STATUS_MISS_KEY_DATA;
				}
				break;	
			}
			
			/*****************************
		  	 * paipai
		  	 ****************************/	
			case '3':
			{
				
				$snoopy->fetch($productURL);	 	 			 			 
	 			$html_content=$snoopy->results;

			/*	if($nickName!=ConvertEncoding(GetDataByRegx($html_content,PAIPAI_NICK_NAME),'GBK'));//PAIPAI_ENCODING))
				{

	                $errmsg->add( 'reg', "添加的商品不属于该店铺,请重新添加" );	 						
	                TransferTo('add_product_1');
					return;	
				}
			*/				 			
				$extProductID = GetPaipaiProductID($html_content);
	
				if(!edp_is_empty_string($extProductID))
				{
					 $productID=$productDAO->GetProductIDByExtID($extProductID,'paipai');
					 if($productID)
					 {
		                $errmsg->add( 'reg', "该商品已添加，<a href=".edp_href_link(PAGENAME_PRODUCT_INFO,"pid=$productID").">点击查看</a>" );	 						
						TransferTo('add_product_1');
						return;		
					 }
					 else
					 {
						$productName=     ConvertEncoding(GetDataByRegx($html_content,PAIPAI_PRODUCT_NAME),'GBK');//PAIPAI_ENCODING);
						$productPicture=  GetDataByRegx($html_content,PAIPAI_PRODUCT_PIC);
						$productPrice=    GetDataByRegx($html_content,PAIPAI_PRODUCT_PRICE);
						//$productLocation productCategory productDesc 
						
						$status = ADDPRODUCT_STATUS_SUCCESS;
						
						if(edp_is_empty_string($productName)||edp_is_empty_string($productPicture)||edp_is_empty_string($productPrice))
						{
		      	      		$status = ADDPRODUCT_STATUS_MISS_REG_DATA;
				   		}	
						
					 }
				}
				else
				{
					$status = ADDPRODUCT_STATUS_MISS_KEY_DATA;
				}
				break;	
			}
			
			/*****************************
	  	     * youa
	  	     ****************************/	
			case '4':
			{
				$snoopy->fetch($productURL);	 	 			 			 
 				$html_content=$snoopy->results;
 				
			/*	if($nickName!=ConvertEncoding(GetDataByRegx($html_content,YOUA_NICK_NAME),'GBK'))//YOUA_ENCODING))
				{
	                $errmsg->add( 'reg', "添加的商品不属于该店铺,请重新添加" );	 						
	                TransferTo('add_product_1');
					return;	
				}
			*/
				$extProductID = GetYouaProductID($html_content);

				if(!edp_is_empty_string($extProductID))
				{
					 $productID=$productDAO->GetProductIDByExtID($extProductID,'youa');
					 if($productID)
					 {
		                $errmsg->add( 'reg', "该商品已添加，<a href=".edp_href_link(PAGENAME_PRODUCT_INFO,"pid=$productID").">点击查看</a>" );	 						
						TransferTo('add_product_1');
						return;		
					 }
					 else
					 {

						$productName=     ConvertEncoding(GetDataByRegx($html_content,YOUA_PRODUCT_NAME),'GBK');//YOUA_ENCODING);
						$productPicture=  GetDataByRegx($html_content,YOUA_PRODUCT_PIC);
						$productPrice=    GetDataByRegx($html_content,YOUA_PRODUCT_PRICE);
						//$productLocation productCategory productDesc 				                            
						
						$status = ADDPRODUCT_STATUS_SUCCESS;
						
						if(edp_is_empty_string($productName)||edp_is_empty_string($productPicture)||
						   edp_is_empty_string($productPrice))
						{
		      	      		$status = ADDPRODUCT_STATUS_MISS_REG_DATA;
				   		}	
						
					 }
				}
				else
				{
					$status = ADDPRODUCT_STATUS_MISS_KEY_DATA;
				}
				break;	
			}

			/*****************************
	  	     * B2C
	  	     ****************************/	
			case '100':
			{				
				$productID=$productDAO->GetProductIDByURL($productURL,'b2c');

				//可以考虑细分，把比较小的多个商城的extentid存在一个平台(100,110,120)里. 
				//支持的采用array(sid=>,plat_code=>}，if $sid in array, GetProductIDByExtID else GetProductIDByURL
				
				if($productID)
				{
	                $errmsg->add( 'reg', "该商品已添加，<a href=".edp_href_link(PAGENAME_PRODUCT_INFO,"pid=$productID").">点击查看</a>" );	 						
					TransferTo('add_product_1');
					return;					
				}
				else
				{
					/**
					 * productID不存在有2种情况
					 * 1.该产品不存在，url 不会存在product_info_b2c表中，查询不到
					 * 2.该产品其实存在，但是由于url不同，导致查询不到
					 * 对于情况2，会完成添加产品的步骤，需要经常审核正则的正确性，通过用户报错和人工合并数据
					 */
					$status = ADDPRODUCT_STATUS_SUCCESS;
	   				break;
				}
			}
			
			/*****************************
	  	     * 目前支持：101dangdang,102amazon,103360buy,104yihaodian
	  	     * 添加步骤，1.添加product_info_**表，2.添加正则支持 3.shop_platform添加平台 4.添加拼接url函数）
	  	     ****************************/	
			case ($platID > '100'):
			{	
									 			
	 			$plat_code = $shopDAO->GetShopPlatCode($platID);	 			
	 			
	 			//先通过URL获取productID
	 			$extProductID = GetB2CProductIDByURL($plat_code,$productURL);
		 				
	 			if(edp_is_empty_string($extProductID)){

		 		    //通过html获取productID
		 		    $reg = strtoupper($plat_code)."_PRODUCTID";
					$snoopy->fetch($productURL);	 	 			 			 
		 			$html_content=$snoopy->results; 
		 		    $extProductID=GetDataByRegx($html_content,constant($reg)); 			
								 					
	 			}		 				 		
		 		
		 		if(!edp_is_empty_string($extProductID))
				{
			 		$productID=$productDAO->GetProductIDByExtID($extProductID,$plat_code);
		 			 			
					if($productID)
					{
		                $errmsg->add( 'reg', "该商品已添加，<a href=".edp_href_link(PAGENAME_PRODUCT_INFO,"pid=$productID").">点击查看</a>" );	 						
						TransferTo('add_product_1');
						return;					
					}
					else
					{						
						$status = ADDPRODUCT_STATUS_SUCCESS;
					}
						
				}else{
										
					$status = ADDPRODUCT_STATUS_MISS_KEY_DATA;
				}		
				
				edp_setsession('plat_code',$plat_code);
				
				break;
			}
					
			default:
			{
				$status = ADDPRODUCT_STATUS_MISS_KEY_DATA;
				break; 
			}
		}

	    edp_setsession('productURL',$productURL);
	  	edp_setsession('sid',$sid);
	  	edp_setsession('extProductID',$extProductID);
	  	edp_setsession('status',$status);
		edp_setsession('platID',$platID);	
		
	    TransferTo('add_product_2');
	}

		
	function ProcessAddProduct()
	{
		global 	$sid,$productURL,$status,$extProductID, $nickName,$platID,
		        $productName, $productLocation, $productPicture,$productPrice,$productCategory,$productDesc,
		        $shopDAO, $productDAO, $cityDAO, $productCategoryDAO, $errmsg;
         // productDesc = '';   
				    	
		$productName = edp_db_input(trim($_POST['productName']));
		$productLocation = $cityDAO->GetCityID(edp_db_input(trim($_POST['city'])));
		$productPicture = edp_db_input(trim($_POST['productPicture']));
		$productPrice = edp_db_input(trim($_POST['productPrice']));
		$productCategoryName = edp_db_input(trim($_POST['productCategory']));
		$productCategory = $productCategoryDAO->GetProductCategoryIDByName($productCategoryName);

		//$productDesc = $_POST['productDesc']; remove product desc by bo 

		$sid = edp_getsession('sid');		
    	$productURL =   edp_getsession('productURL');	
    	$extProductID = edp_getsession('extProductID');	  
    	$status = edp_getsession('status');	 
    	$platID = edp_getsession('platID');	 
        $userID = edp_getsession('userid');

        
		if(!edp_isset_session('productURL')||!edp_isset_session('sid')||!edp_isset_session('extProductID')||
	       !edp_isset_session('status')||!edp_isset_session('platID')){
	    	
			$errmsg->add( 'reg', '该商品添加过程被中断，请重新添加' );
//	    	if(get_magic_quotes_gpc()){				 
//				$productDesc =   stripslashes($productDesc);					
//			}	remove product desc by bo 			
			TransferTo('add_product_1');
		    return; 	    
	    }
	    
	    if(intval($productCategory)<1 || intval($productCategory)>68){
			
	    	$errmsg->add( 'reg', '商品类别不正确' );    	
	    	TransferTo('add_product_2');
		    return; 
	    }
	    
	    if( IsParaOK() == false )
	    {
//	    	if(get_magic_quotes_gpc()){				 
//				$productDesc =   stripslashes($productDesc);						
//			}	  remove product desc by bo   	
	    	TransferTo('add_product_2');
		    return; 
	    }
	
	//	$productDesc = EdpFilterHtmlTag(edp_db_input(trim($productDesc))); remove product desc by bo 
			    
		switch($platID)
		{
		
			case '0':
			{
				TransferTo('not_allow_add_product');				  
				break;
			}
					
			case '1':
			{				
				$productDetailURL='';
				
				if(edp_isset_session('productDetailURL'))
					$productDetailURL = edp_getsession('productDetailURL');//api返回的正常的url
				
				$clickURL = '';	
				if(edp_isset_session('clickURL'))					
					$clickURL = edp_getsession('clickURL');

				//不需要拼接URL，存入数据库的已经是正常的URL
				$productID = $productDAO->InsertTaobaoProductData($productCategory,$sid,$productName,$productDetailURL, $productPicture, 
													 $productLocation, $productPrice, $productDesc, $status, $userID, $extProductID,
													 $clickURL,'0' );
													 										
				edp_unset_session('productDetailURL');
				//edp_unset_session('productNumID');				
				edp_unset_session('clickURL');
													 
				break;	
			}
			case '2':
			{
				//重新拼接正常的URL
				$productURL = GetGeneralProductURL($platID,$extProductID,$productURL);
				
				$productID = $productDAO->InsertEachnetProductData($productCategory,$sid,$productName,$productURL, $productPicture, 
												      $productLocation, $productPrice, $productDesc, $status, $userID, $extProductID );
				break;	
			}
			case '3':
			{
				//重新拼接正常的URL
				$productURL = GetGeneralProductURL($platID,$extProductID,$productURL);
				
				$productID = $productDAO->InsertPaipaiProductData($productCategory,$sid,$productName,$productURL, $productPicture, 
													$productLocation, $productPrice, $productDesc, $status, $userID, $extProductID ); 
				break;	
			}
			case '4':
			{
				//重新拼接正常的URL
				$productURL = GetGeneralProductURL($platID,$extProductID,$productURL);
				
				$productID = $productDAO->InsertYouaProductData($productCategory,$sid,$productName,$productURL, $productPicture, 
													$productLocation, $productPrice, $productDesc, $status, $userID, $extProductID ); 
				break;	
			}

			case '100':
			{
				/*********
				 * 重新拼接正常的URL，必须得分出新平台后才能
				 **********/
				
				$productID = $productDAO->InsertB2CProductData($productCategory,$sid,$productName,$productURL, $productPicture, 
												  $productLocation, $productPrice, $productDesc, $status, $userID);
				break;
			}

			case ($platID > '100'):
			{
				$plat_code = edp_getsession('plat_code');
				
				//重新拼接正常的URL,防止存入带有别人推广链接的URL
				$productURL = GetGeneralProductURL($platID,$extProductID,$productURL);
				
				$productID = $productDAO->InsertOtherB2CProductData($productCategory,$sid,$productName,$productURL, $productPicture, 
												  $productLocation, $productPrice, $productDesc, $status, $userID,$extProductID,$plat_code);
				
				edp_unset_session('plat_code');
				
				break;
			}			
			
			default:{
				return;
			}
		}
		
		
		edp_unset_session('productURL');	
	    edp_unset_session('sid');	
	    edp_unset_session('extProductID');	  
	    edp_unset_session('status');	   
	    edp_unset_session('platID');	

	    
		if($productID&&!edp_is_empty_string($productID)&& $status != ADDPRODUCT_STATUS_MISS_KEY_DATA)
		{			
			//增加product_count
			$userDAO = GetUserDAO();
			$userDAO->IncreaseAddProductCount( $userID );
			
			//Add Event and Contribution
			$eventDispatcher = GetEventDispatcher();
			$para['sid']=$sid;
			$para['pid']=$productID;
			$eventDispatcher->Notify( $userID, ADD_PRODUCT, $para);	
		}
    
	  	edp_redirect(edp_href_link(PAGENAME_PRODUCT_INFO,"pid=$productID"));
	}
	
?>
